//
//  Aria2.swift
//  Aria2Proxy
//
//  Created by 张宇飞 on 2024/11/5.
//

import Foundation

final class Aria2 {
    static let shared = Aria2()
    private var rpcUrl: URL;
    private var token = "";
    
    func setup(host: String, token: String = "") -> Bool {
        guard let h = URL(string: host) else {
            print("Aria2 invalid host: \(host)")
            return false
        }
        self.rpcUrl = h.appending(path: "jsonrpc")
        return true
    }
    
    func sync() {
        // 同步状态
    }
    
    private init() {
        self.rpcUrl = URL(string: "http://127.0.0.1:6800")!.appending(path: "jsonrpc");
    }
    
    func download(task: Aria2Task) async throws -> Bool {
        let method = "system.multicall"
        let files = task.hls.files()
        let params = [files.map({f in
            [
                "methodName": "aria2.addUri",
                "params": [[f], ["dir": task.saveDir]]
            ]
        })]
        
        if let _ = try await self.call(method: method, tid: task.id, params: params) {
            return true
        }
        return false
    }
    
    func start(tid: String) -> Bool {
        return false
    }
    
    func pause(tid: String) -> Bool {
        return false
    }
    
    func remove(tid: String) -> Bool {
        return false
    }
    
    func tell(tid: String) {
        // 获取必要的进度信息
    }
    
    private func call(method: String, tid: String, params: Any) async throws -> [String: Any]? {
        var req = URLRequest(url: self.rpcUrl)
        req.httpMethod = "POST"
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let jdata: [String: Any] = [
            "jsonrpc": "2.0",
            "id": tid,
            "method": method,
            "params": params
        ]
        req.httpBody = try JSONSerialization.data(withJSONObject: jdata)
        
        let (data, _) = try await URLSession.shared.data(for: req)
        return try JSONSerialization.jsonObject(with: data) as? [String: Any]
    }
}
